
<template>
  <div class="min-h-screen bg-gray-50">


    <!-- 页面头部 -->
    <div class="pt-20">
      <div class="bg-gradient-to-r from-blue-600 to-blue-800 text-white py-16">
        <div class="container mx-auto px-12">
          <div class="max-w-4xl">
            <h1 class="text-5xl font-bold mb-6">课程商城</h1>
            <p class="text-xl leading-relaxed mb-8">
              提供直播班级套餐、纯录播课程与增值服务，满足多元学习需求
            </p>
            <div class="flex gap-4">
              <el-button type="primary" size="default" class="rounded px-6 font-medium" @click="startLearning">
                开始学习
              </el-button>
              <el-button size="default" class="border-2 border-white text-black bg-white hover:bg-gray-100 rounded px-6 font-medium">
                查看全部
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 筛选和搜索区域 -->
    <div class="bg-white py-8 shadow-sm">
      <div class="container mx-auto px-12">
        <!-- 顶层两大模块切换（系列课 / 直播班级） -->
        <div class="mb-6">
          <el-tabs v-model="activeTab" class="course-top-tabs">
            <el-tab-pane label="直播班级" name="class" />
            <el-tab-pane label="系列课推荐" name="series" />
          </el-tabs>
        </div>
        <div class="flex items-center justify-between">
          <div class="flex items-center gap-6">
            <div class="flex items-center gap-2">
              <span class="text-sm font-medium text-gray-700">分类:</span>
              <el-select v-model="selectedCategory" placeholder="全部分类" class="w-40" size="default">
                <el-option label="全部分类" value="all" />
                <el-option label="人工智能" value="ai" />
                <el-option label="数据分析" value="data" />
                <el-option label="前端开发" value="frontend" />
                <el-option label="后端开发" value="backend" />
                <el-option label="移动开发" value="mobile" />
                <el-option label="设计美学" value="design" />
              </el-select>
            </div>
            <!-- 顶层选择后，这里只保留分类/难度/排序 -->
            <div class="flex items-center gap-2">
              <span class="text-sm font-medium text-gray-700">难度:</span>
              <el-select v-model="selectedLevel" placeholder="全部难度" class="w-32" size="default">
                <el-option label="全部难度" value="all" />
                <el-option label="入门" value="beginner" />
                <el-option label="进阶" value="intermediate" />
                <el-option label="高级" value="advanced" />
              </el-select>
            </div>
            <div class="flex items-center gap-2">
              <span class="text-sm font-medium text-gray-700">排序:</span>
              <el-select v-model="sortBy" placeholder="最新发布" class="w-32" size="default">
                <el-option label="最新发布" value="latest" />
                <el-option label="最受欢迎" value="popular" />
                <el-option label="价格最低" value="price_low" />
                <el-option label="价格最高" value="price_high" />
              </el-select>
            </div>
          </div>
          <div class="flex items-center gap-4">
            <span class="text-sm text-gray-500">共 {{ filteredCourses.length }} 门课程</span>
            <div class="flex gap-2">
              <el-button 
                :type="viewMode === 'grid' ? 'primary' : ''" 
                size="small" 
                @click="viewMode = 'grid'"
              >
                网格
              </el-button>
              <el-button 
                :type="viewMode === 'list' ? 'primary' : ''" 
                size="small" 
                @click="viewMode = 'list'"
              >
                列表
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 课程列表 -->
    <div class="py-16 bg-white">
      <div class="container mx-auto px-12">
        <!-- 网格视图 -->
        <div v-if="viewMode === 'grid'" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-8">
          <div 
            v-for="course in filteredCourses" 
            :key="course.id"
            class="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden hover:shadow-xl transition-all duration-300 transform hover:-translate-y-2 cursor-pointer"
            @click="viewCourse(course)"
          >
            <div class="h-48 overflow-hidden bg-gradient-to-br from-blue-400 to-blue-600 relative">
              <div class="absolute inset-0 flex items-center justify-center">
                <span class="text-6xl opacity-20">{{ course.icon }}</span>
              </div>
              <div class="absolute top-3 right-3">
                <span class="bg-white bg-opacity-90 text-xs font-medium px-2 py-1 rounded-full text-gray-700">
                  {{ course.level }}
                </span>
              </div>
            </div>
            <div class="p-6">
              <div class="flex items-center gap-2 mb-3">
                <span class="text-xs bg-blue-100 text-blue-600 px-2 py-1 rounded font-medium">
                  {{ course.type === 'class' ? '直播班级套餐' : '系列课' }}
                </span>
                <span v-if="course.type !== 'service'" class="text-xs text-gray-500">共 {{ course.lessonsCount }} 节</span>
              </div>
              <h3 class="text-lg font-bold mb-2 text-gray-900 line-clamp-2">{{ course.title }}</h3>
              <p class="text-sm text-gray-600 mb-4 line-clamp-3">{{ course.description }}</p>
              <div class="flex items-center justify-between mb-4">
                <div class="flex items-center gap-2">
                  <div class="w-8 h-8 bg-gray-200 rounded-full flex items-center justify-center">
                    <span class="text-xs">👨‍🏫</span>
                  </div>
                  <span class="text-sm text-gray-700">{{ course.instructor }}</span>
                </div>
                <div class="flex items-center gap-1">
                  <span class="text-yellow-400">⭐</span>
                  <span class="text-sm font-medium text-gray-700">{{ course.rating }}</span>
                  <span class="text-xs text-gray-500">({{ course.students }})</span>
                </div>
              </div>
              <div class="flex items-center justify-between">
                <div class="flex items-center gap-2">
                  <span class="text-2xl font-bold text-blue-600">¥{{ course.price }}</span>
                  <span v-if="course.originalPrice" class="text-sm text-gray-400 line-through">¥{{ course.originalPrice }}</span>
                </div>
                <div class="flex items-center gap-2">
                  <el-button type="primary" size="small" class="rounded-lg px-4">{{ course.type === 'class' ? '报名班级' : (course.type === 'service' ? '购买服务' : '查看系列') }}</el-button>
                  <el-button v-if="course.type === 'series'" size="small" class="rounded-lg px-3" @click.stop="openTeacherDialog(course)">推荐老师</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 列表视图 -->
        <div v-if="viewMode === 'list'" class="space-y-6">
          <div 
            v-for="course in filteredCourses" 
            :key="course.id"
            class="bg-white rounded-xl shadow-lg border border-gray-100 overflow-hidden hover:shadow-xl transition-all duration-300 cursor-pointer"
            @click="viewCourse(course)"
          >
            <div class="flex">
              <div class="w-64 h-48 bg-gradient-to-br from-blue-400 to-blue-600 relative flex-shrink-0">
                <div class="absolute inset-0 flex items-center justify-center">
                  <span class="text-6xl opacity-20">{{ course.icon }}</span>
                </div>
                <div class="absolute top-3 right-3">
                  <span class="bg-white bg-opacity-90 text-xs font-medium px-2 py-1 rounded-full text-gray-700">
                    {{ course.level }}
                  </span>
                </div>
              </div>
              <div class="flex-1 p-8">
                <div class="flex justify-between items-start mb-4">
                  <div>
                    <div class="flex items-center gap-3 mb-3">
                      <span class="text-sm bg-blue-100 text-blue-600 px-3 py-1 rounded-full font-medium">
                        {{ course.type === 'class' ? '直播班级套餐' : '系列课' }}
                      </span>
                      <span v-if="course.type !== 'service'" class="text-sm text-gray-500">共 {{ course.lessonsCount }} 节</span>
                      <div class="flex items-center gap-1">
                        <span class="text-yellow-400">⭐</span>
                        <span class="text-sm font-medium text-gray-700">{{ course.rating }}</span>
                        <span class="text-xs text-gray-500">({{ course.students }})</span>
                      </div>
                    </div>
                    <h3 class="text-2xl font-bold mb-3 text-gray-900">{{ course.title }}</h3>
                    <p class="text-base text-gray-600 mb-4 leading-relaxed">{{ course.description }}</p>
                    <div class="flex items-center gap-3">
                      <div class="w-10 h-10 bg-gray-200 rounded-full flex items-center justify-center">
                        <span class="text-sm">👨‍🏫</span>
                      </div>
                      <span class="text-base text-gray-700 font-medium">{{ course.instructor }}</span>
                    </div>
                  </div>
                  <div class="text-right">
                    <div class="flex items-center gap-3 mb-4">
                      <span class="text-3xl font-bold text-blue-600">¥{{ course.price }}</span>
                      <span v-if="course.originalPrice" class="text-base text-gray-400 line-through">¥{{ course.originalPrice }}</span>
                    </div>
                    <div class="flex items-center justify-end gap-2">
                      <el-button type="primary" size="large" class="rounded-lg px-8 py-3 font-medium">{{ course.type === 'class' ? '报名班级' : (course.type === 'service' ? '购买服务' : '查看系列') }}</el-button>
                      <el-button v-if="course.type === 'series'" size="small" class="rounded-lg px-3" @click.stop="openTeacherDialog(course)">推荐老师</el-button>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <!-- Teacher dialog -->
  <el-dialog v-model="teacherDialogVisible" width="480px" :show-close="true" align-center>
    <template #header>
      <div class="flex items-center gap-3">
        <span class="text-xl">推荐老师</span>
      </div>
    </template>
    <div v-if="teacherForDialog" class="space-y-3">
      <div class="flex items-center gap-3">
          <div class="w-10 h-10 rounded-full bg-blue-100 flex items-center justify-center text-lg">{{ teacherForDialog.recommendedTeacher?.avatar || '👨‍🏫' }}</div>
        <div>
          <div class="text-base font-semibold text-gray-900">{{ teacherForDialog.recommendedTeacher?.name || teacherForDialog.instructor }}</div>
          <div class="text-xs text-gray-500">{{ teacherForDialog.recommendedTeacher?.title || '授课老师' }}</div>
        </div>
      </div>
      <div class="text-sm text-gray-600">该系列课由老师推荐，建议报名其对应直播班级以获得直播互动与督学服务。</div>
      <div class="flex items-center gap-3">
        <span class="text-sm text-gray-700">选择班级：</span>
        <el-select v-model="selectedClassForTeacher" class="w-64" placeholder="选择班级">
          <el-option v-for="opt in getAllClassesForTeacher(teacherForDialog)" :key="opt.id" :label="opt.label" :value="opt.id"/>
        </el-select>
      </div>
    </div>
    <template #footer>
      <div class="flex items-center justify-end gap-2">
        <el-button @click="teacherDialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmEnrollTeacherClass">查看班级</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Search, User } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 搜索和筛选
const searchText = ref('')
const selectedCategory = ref('all')
const selectedLevel = ref('all')
const activeTab = ref('class')
const sortBy = ref('latest')
const viewMode = ref('grid')

// 课程数据
const courses = ref([
  {
    id: 1,
    title: '人工智能基础与实战 · 系列课',
    description: '从零开始学习人工智能，掌握机器学习、深度学习核心技术，包含实际项目案例',
    category: '人工智能',
    level: '进阶',
    instructor: '李教授',
    lessonsCount: 24,
    rating: 4.9,
    students: 1285,
    price: 599,
    originalPrice: 3999,
    icon: '🤖',
    categoryKey: 'ai',
    type: 'series',
    boundClassId: 11,
    recommendedTeacher: { id: 't-ai', name: '李教授', title: 'AI专家', avatar: '🧠' }
  },
  {
    id: 2,
    title: 'Python直播班级（2025春）',
    description: '使用Python进行数据分析，掌握pandas、numpy、matplotlib等核心库的使用',
    category: '数据分析',
    level: '入门',
    instructor: '张博士',
    lessonsCount: 18,
    rating: 4.8,
    students: 2156,
    price: 999,
    originalPrice: 2499,
    icon: '📊',
    categoryKey: 'data',
    type: 'class'
  },
  {
    id: 9,
    title: '前端工程化直播班（2025夏）',
    description: '系统掌握现代前端工程化：Vite/Webpack、CI/CD、性能优化与质量保障',
    category: '前端开发',
    level: '进阶',
    instructor: '前端讲师团',
    lessonsCount: 24,
    rating: 4.8,
    students: 1689,
    price: 699,
    originalPrice: 3299,
    icon: '🧩',
    categoryKey: 'frontend',
    type: 'class'
  },
  {
    id: 10,
    title: '数据分析就业班（2025暑期）',
    description: '从零到上手商业数据分析，包含Excel/SQL/Python统计、可视化仪表盘',
    category: '数据分析',
    level: '入门',
    instructor: '数据教研组',
    lessonsCount: 20,
    rating: 4.7,
    students: 2012,
    price: 699,
    originalPrice: 2999,
    icon: '📊',
    categoryKey: 'data',
    type: 'class'
  },
  {
    id: 11,
    title: 'AI工程师直播班（2025秋）',
    description: '深度学习/大模型基础与落地案例，含模型微调与部署的完整链路',
    category: '人工智能',
    level: '高级',
    instructor: 'AI专家组',
    lessonsCount: 28,
    rating: 4.9,
    students: 1733,
    price: 1699,
    originalPrice: 3999,
    icon: '🤖',
    categoryKey: 'ai',
    type: 'class'
  },
  {
    id: 12,
    title: '全栈就业班（2025秋）',
    description: 'Node.js + Vue3 全栈项目实战，涵盖接口、数据库、部署与监控',
    category: '后端开发',
    level: '进阶',
    instructor: '全栈特训营',
    lessonsCount: 26,
    rating: 4.6,
    students: 1458,
    price: 1499,
    originalPrice: 3599,
    icon: '🧱',
    categoryKey: 'backend',
    type: 'class'
  },
  {
    id: 3,
    title: 'Vue.js全栈开发 · 系列课',
    description: '掌握Vue.js框架，从基础到高级，包含组件开发、状态管理、路由等核心概念',
    category: '前端开发',
    level: '进阶',
    instructor: '王工程师',
    lessonsCount: 20,
    rating: 4.7,
    students: 1876,
    price: 1299,
    originalPrice: 3199,
    icon: '💻',
    categoryKey: 'frontend',
    type: 'series',
    boundClassId: 9,
    recommendedTeacher: { id: 't-fe', name: '王工程师', title: '全栈讲师', avatar: '💻' }
  },
  {
    id: 4,
    title: 'Node.js后端开发 · 系列课',
    description: '学习Node.js后端开发，包含Express框架、数据库操作、API设计等',
    category: '后端开发',
    level: '进阶',
    instructor: '陈架构师',
    lessonsCount: 22,
    rating: 4.6,
    students: 1432,
    price: 1199,
    originalPrice: 2899,
    icon: '⚙️',
    categoryKey: 'backend',
    type: 'series',
    boundClassId: 12,
    recommendedTeacher: { id: 't-be', name: '陈架构师', title: '后端架构', avatar: '⚙️' }
  },
  {
    id: 5,
    title: 'React Native移动开发 · 系列课',
    description: '使用React Native开发跨平台移动应用，一套代码同时支持iOS和Android',
    category: '移动开发',
    level: '高级',
    instructor: '刘专家',
    lessonsCount: 16,
    rating: 4.5,
    students: 987,
    price: 599,
    originalPrice: 3499,
    icon: '📱',
    categoryKey: 'mobile',
    type: 'series',
    boundClassId: 9,
    recommendedTeacher: { id: 't-mobile', name: '刘专家', title: '移动开发', avatar: '📱' }
  },
  {
    id: 6,
    title: 'UI/UX设计实战 · 系列课',
    description: '学习现代UI/UX设计理念和工具，包含Figma、Sketch等设计软件的使用',
    category: '设计美学',
    level: '入门',
    instructor: '美设计师',
    lessonsCount: 14,
    rating: 4.8,
    students: 1654,
    price: 899,
    originalPrice: 2299,
    icon: '🎨',
    categoryKey: 'design',
    type: 'series',
    boundClassId: 9,
    recommendedTeacher: { id: 't-design', name: '美设计师', title: '资深设计', avatar: '🎨' }
  },
  {
    id: 7,
    title: '区块链技术与应用 · 系列课',
    description: '深入了解区块链技术原理，学习智能合约开发，掌握DeFi应用开发',
    category: '人工智能',
    level: '高级',
    instructor: '区块链专家',
    lessonsCount: 26,
    rating: 4.4,
    students: 756,
    price: 799,
    originalPrice: 3999,
    icon: '⛓️',
    categoryKey: 'ai',
    type: 'series',
    boundClassId: 12,
    recommendedTeacher: { id: 't-chain', name: '区块链专家', title: '区块链工程', avatar: '⛓️' }
  },
  {
    id: 8,
    title: '大数据处理与分析 · 系列课',
    description: '学习大数据处理技术，包含Hadoop、Spark等框架的使用和实战项目',
    category: '数据分析',
    level: '高级',
    instructor: '数据科学家',
    lessonsCount: 28,
    rating: 4.6,
    students: 1123,
    price: 899,
    originalPrice: 4299,
    icon: '📈',
    categoryKey: 'data',
    type: 'series',
    boundClassId: 10,
    recommendedTeacher: { id: 't-zhang', name: '张老师', title: '数据分析讲师', avatar: '📊' }
  }
])

// 筛选后的课程
const getSeriesPrice = (level, lessonsCount) => {
  const levelMap = { '入门': 599, '进阶': 699, '高级': 899 }
  if (levelMap[level]) return levelMap[level]
  if (typeof lessonsCount === 'number') {
    if (lessonsCount <= 16) return 599
    if (lessonsCount <= 24) return 699
    return 899
  }
  return 699
}

const filteredCourses = computed(() => {
  let filtered = courses.value

  // 分类筛选
  if (selectedCategory.value !== 'all') {
    filtered = filtered.filter(course => course.categoryKey === selectedCategory.value)
  }

  // 顶层类型筛选（直播班级优先，系列课为推荐）
  filtered = filtered.filter(course => (course.type || 'series') === activeTab.value)

  // 动态定价：系列课根据难度（优先）或课节数设定三位数价格
  filtered = filtered.map(c => {
    if ((c.type || 'series') === 'series') {
      return { ...c, price: getSeriesPrice(c.level, c.lessonsCount) }
    }
    return c
  })

  // 难度筛选
  if (selectedLevel.value !== 'all') {
    const levelMap = { beginner: '入门', intermediate: '进阶', advanced: '高级' }
    filtered = filtered.filter(course => course.level === levelMap[selectedLevel.value])
  }

  // 搜索筛选
  if (searchText.value.trim()) {
    const searchTerm = searchText.value.toLowerCase()
    filtered = filtered.filter(course => 
      course.title.toLowerCase().includes(searchTerm) ||
      course.description.toLowerCase().includes(searchTerm) ||
      course.category.toLowerCase().includes(searchTerm) ||
      course.instructor.toLowerCase().includes(searchTerm)
    )
  }

  // 排序
  switch (sortBy.value) {
    case 'popular':
      filtered.sort((a, b) => b.students - a.students)
      break
    case 'price_low':
      filtered.sort((a, b) => a.price - b.price)
      break
    case 'price_high':
      filtered.sort((a, b) => b.price - a.price)
      break
    default: // latest
      filtered.sort((a, b) => b.id - a.id)
  }

  return filtered
})

// 方法
const viewCourse = (course) => {
  if (course.type === 'class') {
    router.push(`/classes/${course.id}/intro?type=class`)
    return
  }
  router.push(`/courses/${course.id}/series?type=series`)
}

const startLearning = () => {
  router.push('/study')
}

const goToProfile = () => {
  router.push('/profile')
}

const openSocial = (platform) => {
  switch (platform) {
    case 'email':
      window.location.href = 'mailto:service@edulivelink.com'
      break
    case 'wechat':
      ElMessage.info('请扫描二维码关注我们的微信公众号')
      break
    case 'weibo':
      ElMessage.info('请关注我们的官方微博')
      break
  }
}

const goToBoundClass = (classId) => {
  router.push(`/classes/${classId}/intro?type=class`)
}

// 推荐老师弹窗（带班级下拉选择）
const teacherDialogVisible = ref(false)
const teacherForDialog = ref(null)
const selectedClassForTeacher = ref()
const teacherIdToClasses = {
  't-ai': [
    { id: 11, label: 'AI工程师直播班（2025秋）' }
  ],
  't-fe': [
    { id: 9, label: '前端工程化直播班（2025夏）' },
    { id: 12, label: '全栈就业班（2025秋）' }
  ],
  't-be': [
    { id: 12, label: '全栈就业班（2025秋）' }
  ],
  't-mobile': [
    { id: 9, label: '前端工程化直播班（2025夏）' }
  ],
  't-design': [
    { id: 9, label: '前端工程化直播班（2025夏）' }
  ],
  't-chain': [
    { id: 12, label: '全栈就业班（2025秋）' }
  ],
  't-data': [
    { id: 10, label: '数据分析就业班（2025暑期）' }
  ]
  ,
  't-zhang': [
    { id: 10, label: '数据分析就业班（2025暑期）' },
    { id: 2, label: 'Python直播班级（2025春）' }
  ]
}
const openTeacherDialog = (course) => {
  teacherForDialog.value = course
  const tid = course.recommendedTeacher?.id
  const list = tid ? teacherIdToClasses[tid] : []
  selectedClassForTeacher.value = list && list.length ? list[0].id : course.boundClassId
  teacherDialogVisible.value = true
}
const confirmEnrollTeacherClass = () => {
  if (selectedClassForTeacher.value) {
    router.push(`/classes/${selectedClassForTeacher.value}/intro?type=class`)
  }
  teacherDialogVisible.value = false
}

const getAllClassesForTeacher = (course) => {
  const tid = course?.recommendedTeacher?.id
  return tid ? (teacherIdToClasses[tid] || []) : []
}

// 保持用户在课程商城的模块选择：根据路由query.type设置当前Tab
onMounted(() => {
  const t = route.query?.type
  if (t === 'class' || t === 'series') {
    activeTab.value = t
  }
})

watch(() => route.query?.type, (t) => {
  if (t === 'class' || t === 'series') {
    activeTab.value = t
  }
})
</script>

<style scoped>
.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}
</style>
